package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.NewsListViewAdapter;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.News;
import com.smartrobot.smartrobot.view.ExListView;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/1/13.
 */
public class FashionActivity extends Activity implements View.OnClickListener{

    private ExListView listView;
    private NewsListViewAdapter adapter;
    private ImageView back;
    private List<News> newsList;
    private Map<String,String> map;
    private TextView progressTxt;
    private FashionHandler handler;
    private String fileName = FileUtil.newsCachePath + FileUtil.fashionEndName;
    private boolean isGetFashion = false;

    private final int HANDLER_READ_FILE = 1111;
    private final int HANDLER_READ_SERVER = 1112;
    private final int HANDLER_UPDATE_NEW = 1113;
    private final int HANDLER_UPDATE_OLD = 1114;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){

            Log.e("==============>","调用了重启123456789");
            throw new NullPointerException();

        }
        this.setContentView(R.layout.page_fashion);


        init();

    }

    void init(){

        HttpUtil.init(getApplicationContext());
        LogToSd.log_init();
        initView();

    }

    void initView(){

        listView = (ExListView)findViewById(R.id.fashion_listview);
        back = (ImageView)findViewById(R.id.fashion_back);
        progressTxt = (TextView)findViewById(R.id.fashion_progress_txt);

        newsList = new ArrayList<News>();
        handler = new FashionHandler();

        adapter = new NewsListViewAdapter(getApplicationContext(),listView);
        back.setOnClickListener(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(adapter);
        listView.setOnScrollListener(adapter);
        listView.setOnUdateNewListender(new ExListView.UdateNewListener() {
            @Override
            public void updateNew() {

                //更新新的
                Message msg = new Message();
                msg.what = HANDLER_UPDATE_NEW;
                handler.sendMessage(msg);

            }
        });

        listView.setOnUdateOldListener(new ExListView.UdateOldListener() {
            @Override
            public void updateOld() {
                //查看旧的
                Message msg = new Message();
                msg.what = HANDLER_UPDATE_OLD;
                handler.sendMessage(msg);
            }
        });

        Thread thread = new Thread(new FashionInitThread());
        thread.start();


    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.fashion_back:

                FashionActivity.this.finish();

                break;

        }

    }

    class FashionInitThread implements Runnable{

        @Override
        public void run() {

            Looper.prepare();

            if(new File(fileName).exists()) {
                newsList = FileUtil.readNewsFromFile(fileName);
                Message msg = new Message();
                msg.what = HANDLER_READ_FILE;
                handler.sendMessage(msg);
            }
            else {
                Message msg = new Message();
                msg.what = HANDLER_READ_SERVER;
                handler.sendMessage(msg);

            }

            }
        }


    /**
     * 更新界面
     */
    class FashionHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {

            switch (msg.what) {

                case HANDLER_READ_FILE:

                    Log.e("=============>", "读取文件");
                    if(newsList.size() == 0){
                            isGetFashion = true;
                            map = new HashMap<String, String>();
                            map.put("classify", "0");
                            map.put("lastTime", "1");
                            map.put("num", "10");
                            map.put("way", "up");
                            newsList.clear();
                            HttpUtil.apiGetNews(map, newsList, handler);
                    }else{
                        isGetFashion = false;
                        adapter.notiOldDataChange(newsList);
                        progressTxt.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);
                    }




                    break;

                case HANDLER_READ_SERVER:

                    Log.e("=============>", "读取服务器内容");

                    if(!isGetFashion){
                        isGetFashion = true;
                        map = new HashMap<String, String>();
                        map.put("classify", "0");
                        map.put("lastTime", "1");
                        map.put("num", "10");
                        map.put("way", "up");
                        newsList.clear();
                        HttpUtil.apiGetNews(map, newsList, handler);
                    }


                    break;

                case HANDLER_UPDATE_NEW:

                    Log.e("=============>", "读取服务器最新的内容");
                    if(!isGetFashion) {
                        isGetFashion = true;
                        map = new HashMap<String, String>();
                        map.put("classify", "0");
                        map.put("lastTime", adapter.getNewUpdateTime());
                        map.put("num", "10");
                        map.put("way", "up");
                        newsList.clear();
                        HttpUtil.apiGetNews(map, newsList, handler);
                    }
                    break;


                case HANDLER_UPDATE_OLD:

                    Log.e("=============>", "读取服务器旧的内容");
                    if(!isGetFashion) {
                        isGetFashion = true;
                        map = new HashMap<String, String>();
                        map.put("classify", "0");
                        map.put("lastTime", adapter.getOldUpdateTime());
                        map.put("num", "10");
                        map.put("way", "low");
                        newsList.clear();
                        HttpUtil.apiGetNews(map, newsList, handler);
                    }

                    break;

                case HttpUtil.GET_NEWS_SUCCESS:

                    Log.e("=============>", "成功从服务器获取内容");
                    if (msg.obj.toString().equals("up")) {
                        adapter.notiNewDataChange(newsList);
                    } else {
                        adapter.notiOldDataChange(newsList);
                    }
                    isGetFashion = false;
                    listView.changeState();
                    listView.hiddenFooter();
                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);


                    break;

                case HttpUtil.GET_NEWS_FAILD:


                    if (msg.obj != null) {
//                        if (msg.arg1 == 0)
//                            ToastCustom.showToast(getApplicationContext(), "没有了╮(╯▽╰)╭");
                    }
                       else {
                        ToastCustom.showToast(getApplicationContext(),"连接服务器异常，请稍后再试!");
                    }
                    isGetFashion = false;
                    listView.changeState();
                    listView.hiddenFooter();
                    progressTxt.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                    break;






            }


        }
    }

    @Override
    protected void onRestart() {
        //重新初始化
        if(newsList == null)
            newsList = new ArrayList<News>();
        if(handler == null)
            handler = new FashionHandler();
        HttpUtil.init(getApplicationContext());

        super.onRestart();
    }

    void close(){

        newsList.clear();
        if(newsList != null)
        newsList = null;

    }


    @Override
    protected void onDestroy() {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                //开启线程保存文件
                adapter.saveCircleToFile(fileName);
                Log.e("=========>","保存成功"+fileName);

            }
        });
        thread.start();
        close();

        super.onDestroy();
    }
}



